package com.leeyu.service.impl;

import com.leeyu.rabbitmq.config.RabbitMQConfig;
import com.leeyu.mapper.OrderManageMapper;
import com.leeyu.service.OrderManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Slf4j
@Service
public class OrderManageServiceImpl implements OrderManageService {

    @Autowired
    private OrderManageMapper orderManageMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void save() {
        // 创建订单
        String orderId = UUID.randomUUID().toString().replaceAll("-", "");
        orderManageMapper.save(orderId);

        // 发送延迟消息
        rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_EXCHANGE, "", orderId, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 延迟一分钟，如果未支付取消订单
                message.getMessageProperties().setExpiration("60000");
                return message;
            }
        });

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelOrder(String orderId) {
        // 行锁
        int orderState = orderManageMapper.getOrderStateByIdForUpdate(orderId);
        if (orderState != 0) {
            log.info("订单已支付！");
            return;
        }

        log.info("订单超时未支付，即将取消订单！ 订单ID: {}", orderId);
        orderManageMapper.updateOrderStateById(orderId, -1);
    }
}
